import React, { useState, useImperativeHandle, useEffect, useRef, forwardRef } from 'react';

const Child = forwardRef((props, refParam)=>{
    console.log(props);
    const inputRef = useRef();
    useImperativeHandle(refParam, ()=>{
        return {
            focus:()=>{
                inputRef.current.focus();
            },
            logSon:()=>{
                
                return refParam;
            }
        }
    },[])
    return (
        <div>
            <input  defaultValue={props.value} ref={inputRef} />
            <button onClick={()=>console.log(inputRef)}>打印ref</button>
        </div>
    )
})

const Parent = ()=>{
    const sonRef = useRef();
    useEffect(()=>{
        console.log(sonRef);
        
    },[])
    return (
        <>
            <Child ref={sonRef} value='hello world' />
            <div>
                <button onClick={()=>sonRef.current.focus()}>获取子组件的input元素</button>
            </div>
        </>
    )
}

export default Parent;